package exam.alipay;


import com.alibaba.fastjson.JSON;
import com.alibaba.fastjson.JSONObject;
import com.alipay.api.AlipayApiException;
import com.alipay.api.AlipayClient;
import com.alipay.api.DefaultAlipayClient;

import com.alipay.api.domain.AlipayTradePrecreateModel;
import com.alipay.api.request.AlipayTradePrecreateRequest;
import com.alipay.api.response.AlipayTradePrecreateResponse;
import com.alipay.api.request.AlipayOpenPublicTemplateMessageIndustryModifyRequest;
import com.alipay.api.request.AlipayTradePagePayRequest;
import com.alipay.api.response.AlipayOpenPublicTemplateMessageIndustryModifyResponse;
import com.alipay.api.response.AlipayTradePagePayResponse;
import com.alipay.demo.trade.model.builder.AlipayTradePrecreateRequestBuilder;
import com.alipay.demo.trade.model.result.AlipayF2FPrecreateResult;
import com.alipay.demo.trade.service.AlipayTradeService;
import com.alipay.demo.trade.service.impl.AlipayTradeServiceImpl;
import com.baomidou.mybatisplus.extension.exceptions.ApiException;
import exam.alipay.domain.AlipayBean;
import exam.alipay.domain.Pay;
import exam.alipay.domain.PayRecord;
import exam.alipay.service.PayRecordService;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.Configuration;
import org.springframework.stereotype.Component;

import java.text.SimpleDateFormat;
import java.util.Date;

/**
 * @author Xiongx
 * @version 1.0
 * @date 2021/4/9 18:43
 * @since JDK 1.8
 *
 * 阿里支付测试
 */
@Component
@Slf4j
public class AliPay {


    @Autowired
    private PayRecordService payRecordService;

    /**
     * 支付接口
     * @param alipayBean
     * @return
     * @throws AlipayApiException
     */
    public String pay(AlipayBean alipayBean) throws AlipayApiException {
        // 1、获得初始化的AlipayClient
        String serverUrl = AlipayProperties.getGatewayUrl();
        String appId = AlipayProperties.getAppId();
        String privateKey = AlipayProperties.getPrivateKey();
        String format = "json";
        String charset = AlipayProperties.getCharset();
        String alipayPublicKey = AlipayProperties.getPublicKey();
       String signType = AlipayProperties.getSignType();
//        String returnUrl = AlipayProperties.getReturnUrl();
//        String notifyUrl = AlipayProperties.getNotifyUrl();
        AlipayClient alipayClient = new DefaultAlipayClient(serverUrl, appId, privateKey, format, charset, alipayPublicKey, signType);
        // 2、设置请求参数
        AlipayTradePagePayRequest alipayRequest = new AlipayTradePagePayRequest();
//        // 页面跳转同步通知页面路径
//        alipayRequest.setReturnUrl(returnUrl);
//        // 服务器异步通知页面路径
//        alipayRequest.setNotifyUrl(notifyUrl);
        // 封装参数
        alipayRequest.setBizContent(JSON.toJSONString(alipayBean));
        // 3、请求支付宝进行付款，并获取支付结果

        AlipayTradePagePayResponse response=alipayClient.pageExecute(alipayRequest);

        String result = response.getSubCode();
        System.out.println(result);
        // 返回付款信息
        return result;
    }


    public String payQrCode(AlipayBean alipayBean){
        // 1、获得初始化的AlipayClient
        String serverUrl = AlipayProperties.getGatewayUrl();
        String appId = AlipayProperties.getAppId();
        String privateKey = AlipayProperties.getPrivateKey();
        String format = "json";
        String charset = AlipayProperties.getCharset();
        String alipayPublicKey = AlipayProperties.getPublicKey();
        String signType = AlipayProperties.getSignType();
//        String returnUrl = AlipayProperties.getReturnUrl();
//        String notifyUrl = AlipayProperties.getNotifyUrl();
        AlipayClient alipayClient = new DefaultAlipayClient(serverUrl, appId, privateKey, format, charset, alipayPublicKey, signType);
        //设置请求参数
        AlipayTradePrecreateRequest request = new AlipayTradePrecreateRequest();
        AlipayTradePrecreateModel model = new AlipayTradePrecreateModel();

        SimpleDateFormat simpleDateFormat=new SimpleDateFormat("yyyyMMddHHmmss");
        String str=simpleDateFormat.format(new Date());
        str+=(int)((Math.random()*9+1)*10000000);
        model.setOutTradeNo(str);
        model.setTotalAmount(alipayBean.getTotal_amount());
        model.setSubject(alipayBean.getSubject());
        //如果没有店铺号可不设置
        model.setStoreId("9527");
        model.setQrCodeTimeoutExpress("10m");
        request.setBizModel(model);
        boolean flag=false;
        //支付宝异步通知地址
        log.info("创建支付宝订单，请求参数：{} ", JSONObject.toJSONString(request));
        AlipayTradePrecreateResponse response=null;
        //调用接口
        try {
            response= alipayClient.execute(request);
            log.info("创建支付宝订单，返回值：{} ", JSONObject.toJSONString(response));

            log.info("交易订单号outTradeNo：{} ", response.getOutTradeNo());
            log.info("支付二维码qrCode：{} ", response.getQrCode());
        }catch (AlipayApiException e){
            e.printStackTrace();
            flag=true;
        }
        if(!flag){
            PayRecord payRecord=PayRecord.builder().subject(isNull(alipayBean.getSubject()))
                    .outTradeNo(str).totalMount(isNull(alipayBean.getTotal_amount()))
                    .body(isNull(alipayBean.getBody())).build();
            payRecordService.save(payRecord);
            return response.getQrCode();
        }
        return "";
    }

    public String isNull(String str){
        return str==null?"":str;
    }





}
